
# get_word_count method, input word, output dictionary
# 如果字符串只有字母，返回字母的个数
# 如果字符串中有字母和数字，那么这个数字就是字母的个数
# 如果字符串中含有字母、数字之外的字符，忽略这些字符
# input "A", output {"A":1}
# input "AA", output {"A":2}
# input "AAB", output {"A":2, "B":1}
# input "A-2", output {"A":2}
# input "B:3", output {"B":3}
# input "E=5", output {"E":5}
def get_word_count(word):
    #创建一个字典
    word_count = {}
    #遍历字符串
    for letter in word:
        #如果是字母
        if letter.isalpha():
            #如果字母在字典中
            if letter in word_count:
                #字母的个数加1
                word_count[letter] += 1
            else:
                #字母的个数为1
                word_count[letter] = 1
        #如果是数字
        elif letter.isdigit():
            #字母的个数为数字
            word_count[word[0]] = int(letter)
    return word_count

# letter_count method, input string, output dictionary
# the string can be splited by space, and each word should be passed to get_word_count method
# input "A B", output {"A":1, "B":1}
# input "A B2", output {"A":1, "B":2}
# input "A B2 C:3", output {"A":1, "B":2, "C":3}
# input "A B2 C:3 D=4", output {"A":1, "B":2, "C":3, "D":4}
# if the keys are same, their values should be added
# input "A B2 B", output {"A":1, "B":3}
def letter_count(string):
    #创建一个字典
    letter_count = {}
    #将字符串按空格分割
    words = string.split(" ")
    #遍历分割后的字符串
    for word in words:
        #调用get_word_count方法
        word_count = get_word_count(word)
        #遍历返回的字典
        for key in word_count:
            #如果字典中有这个字母
            if key in letter_count:
                #字母的个数相加
                letter_count[key] += word_count[key]
            else:
                #字母的个数为返回的字典中的个数
                letter_count[key] = word_count[key]
    return letter_count
